package cn.itlaobing.service;

import cn.itlaobing.entity.Gender;
import cn.itlaobing.entity.UserEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Berlin-IOU on 2017/12/5.
 */
@Service
public class UserService implements BaseService {
    private List<UserEntity> list = new ArrayList<>();

    public UserService() {
        for (int i = 0; i < 10; i++) {
            UserEntity userEntity = new UserEntity();
            userEntity.setId(Long.valueOf(i));
            userEntity.setName("USER" + i);
            userEntity.setBirthday(new Date());
            userEntity.setGender(Gender.FEMALE);
            list.add(userEntity);
        }
    }

    @Override
    public List<UserEntity> findAll() {
        return list;
    }

    @Override
    public UserEntity findById(Long id) {
        for (UserEntity user : list) {
            if (user.getId().equals(id)) {
                return user;
            }
        }
        return null;
    }

    @Override
    public UserEntity saveOrUpdate(UserEntity userEntity) {
        if (userEntity.getId() != null) {
            UserEntity user = findById(userEntity.getId());
            if (user != null) {
                user.setName(userEntity.getName());
                user.setGender(userEntity.getGender());
                user.setBirthday(userEntity.getBirthday());
            }
        } else {
            userEntity.setId(Long.valueOf(list.size()*100+1 ));
            list.add(userEntity);
        }
        return userEntity;
    }

    @Override
    public void deleteById(Long id) {
        UserEntity userEntity=findById(id);
        list.remove(userEntity);
    }
}
